package com.hfjyz.registration.task;

import com.hfjyz.registration.model.OrderInfo;
import com.hfjyz.registration.service.OrderInfoService;
import com.hfjyz.registration.util.ExamProperties;
import com.hfjyz.registration.util.OrderPaySearchFromBank;

public class OrderPaySearchingTask implements Task {
	private static final int SEARCH_COUNT = 20;
	private ExamProperties properties;
	private OrderInfoService orderInfoService;
	private String orderId;

	public OrderPaySearchingTask(String orderId,
			OrderInfoService orderInfoService, ExamProperties examProperties) {
		this.orderId = orderId;
		this.orderInfoService = orderInfoService;
		this.properties = examProperties;
	}

	@Override
	public int execute() {
		OrderInfo o;
		try {
			o = orderInfoService.getOrderInfo(orderId);
		} catch (Exception e) {
			o = null;
		}
		if (o == null || o.getOrderState() != 3) {
			return 0; // order already deleted
		}
		try {
			o.setSearchBankCount(o.getSearchBankCount() + 1);

			int result = OrderPaySearchFromBank.getBankResult(o, properties);
			if (result == 1) {
				o.setOrderState(2);
			} else if (result == 2 && o.getSearchBankCount() >= SEARCH_COUNT) {
				o.setOrderState(0);
			}
			orderInfoService.updateOrder(o, false);

			return  o.getSearchBankCount() >= SEARCH_COUNT && result == 2 ? 1 : result;
		} catch (Exception e) {
			e.printStackTrace();
			return 1;
		}
	}

}
